import { ApiCall } from "tsrpc";
import { ReqSend, ResSend } from "../../shared/api_client/mail/PtlSend";
import player from "../../core/rpg/entity/player";
import sdk from '../../core/index';
import { ComType } from "../../core/tool/component";
import bag_component from "../../component/bag_component";
import MailManage from "../../core/manage/MailManage";
import { Item } from "../../shared/face";

export default async function (call: ApiCall<ReqSend, ResSend>) {
    let _player = call.req._player as player;
    let com = _player.getComponent(ComType.背包) as bag_component;
    
    // 参数验证
    if (!call.req.title || !call.req.to_id || !call.req.msg) {
        call.error('邮件标题、收件人和内容不能为空');
        return;
    }
    
    // 检查收件人是否存在
    // const targetPlayer = UserManager.get_player(call.req.to_id);
    // if (!targetPlayer) {
    //     call.error('收件人不存在');
    //     return;
    // }
    
    // 不能给自己发邮件
    // if (call.req.to_id === _player.id) {
    //     call.error('不能给自己发送邮件');
    //     return;
    // }
    
    // 处理附件物品
    const items: Item[] = [];
    if (call.req.items && call.req.items.length > 0) {
        for (const itemReq of call.req.items) {
            // 检查背包中是否有该物品
            const bagItem = com.findItem_id(itemReq.id, itemReq.type);
            if (!bagItem) {
                call.error(`物品 ${itemReq.id} 不存在`);
                continue;
            }
            
            // 如果数量不足，使用道具最大数量
            const actualCount = Math.min(bagItem.count, itemReq.cont);
            
            // 从背包中移除物品
            com.delItem(bagItem, actualCount);
            
            // 创建邮件附件物品
            const mailItem: Item = {
                quality: bagItem.quality,
                uuid: bagItem.uuid,
                emoji: bagItem.emoji,
                icon: bagItem.icon,
                id: bagItem.id,
                name: bagItem.name,
                desc: bagItem.desc,
                type: bagItem.type,
                count: actualCount,
                data: bagItem.data
            };
            items.push(mailItem);
        }
    }
    
    try {
        // 发送邮件（7天过期）
        MailManage.send(
            _player.id,           // 发件人
            call.req.to_id,       // 收件人
            7,                    // 过期天数
            call.req.title,       // 标题
            call.req.msg,         // 内容
            items                 // 附件
        );
        
        call.succ({});
    } catch (error) {
        // 如果发送失败，将物品返还给发件人
        for (const item of items) {
            com.addItem(item);
        }
        call.error('发送邮件失败');
    }
}
